package fw.asmx.appstoper.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

import fw.asmx.appstoper.MainActivity;
import fw.asmx.appstoper.R;
import fw.asmx.appstoper.adapter.item.AppItem;

public class AppListAdapter extends RecyclerView.Adapter<AppListAdapter.ViewHolder>
{
    private MainActivity activity;
    public List<AppItem> lst;

    private OnItemClickListener onItemClickListener;

    public AppListAdapter(MainActivity activity,List<AppItem> lst)
    {
        this.activity=activity;
        this.lst = lst;
    }

    @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
    {
        View v = LayoutInflater.from(parent.getContext())
                               .inflate(R.layout.item_applist, parent, false);
        return new ViewHolder(v);
    }

    @Override public void onBindViewHolder(ViewHolder vh, int pos)
    {
        AppItem ai = lst.get(pos);
        vh.ivIcon.setImageDrawable(ai.icon);
        vh.tvName.setText(ai.appName);
        vh.cb.setChecked(activity.chkedMap.get(ai.pkgName));
    }

    @Override public int getItemCount()
    {
        return lst.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
    {
        public ImageView ivIcon;
        public TextView tvName;
        public CheckBox cb;

        public ViewHolder(View v)
        {
            super(v);
            ivIcon = (ImageView) v.findViewById(R.id.iv_icon);
            tvName = (TextView) v.findViewById(R.id.tv_name);
            cb = (CheckBox) v.findViewById(R.id.cb);
            v.setOnClickListener(this);
            v.setTag(this);
        }

        @Override public void onClick(View v)
        {
            if (onItemClickListener != null)
            {
                int pos = getAdapterPosition();
                onItemClickListener.onItemClick(v, lst.get(pos), pos);
            }
        }
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener)
    {
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener
    {
        void onItemClick(View v, AppItem ai, int pos);
    }
}
